package com.yuan.ayuancity.controller.common;

import com.yuan.view.YuancityView;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 *          图片上传控制器
 * </p>
 *
 * @author asuyuan
 * @since 2023/2/16
 */
@Api(tags = "图片上传控制器")
@RestController()
@RequestMapping("/city/v1")
@CrossOrigin
public class UploadController {

    @PostMapping("/uploadImage")
    public YuancityView uploadImage(@RequestParam("fileList") MultipartFile multipartFile) throws IOException {
        if (multipartFile.isEmpty()){
            return YuancityView.failure("图片为空~");
        }
        //获取文件名 XXX.png
        String filename = multipartFile.getOriginalFilename();
        //获取文件后缀 png,jpg
        String suffixName  = filename.substring(filename.lastIndexOf("."));
        String contentType = multipartFile.getContentType();
        if (suffixName .equals(".png")||suffixName .equals(".jpg")){
            //获取项目image路径,将文件保存到改路径
            /**
             * 法一 /D:/Idea/..../springboot/target/classes/
            String url= getClass().getClassLoader().getResource("static/image").getPath();
             */
            /**
             * 法二  /D:/Idea/.../springboot
             */
             String property = System.getProperty("user.dir");
             String url = property + "/src/main/resources/static/image/";

             //利用UUID修改文件名
           String newFilename= UUID.randomUUID()+suffixName;
            //声明文件
            File file=new File(url+newFilename);
            //判断是否有该路径,没有则创建
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            //上传文件
            multipartFile.transferTo(file);
            System.out.println("上传文件："+filename);
            System.out.println("文件名："+newFilename+" url:"+url+newFilename);
            return YuancityView.success("上传成功").put("url","/image/"+newFilename);
        }
        return YuancityView.failure("图片格式错误~");
    }
}
